import mod_item
from mod_ai import AIBrain
from items.vibrosword import Whack
import mod_actor

class JanitorBrain(AIBrain):
    def lookForGrabbableItems(self):
        levelMemory = self.memory.getLevelMemory(self.actor.location[0].number)
        retVal = []
        for tile in levelMemory.itemMap:
            items = levelMemory.itemMap[tile]
            grabbable = False
            for item in items:
                if item.grabbable:
                    grabbable = True
                    break
            if grabbable:
                retVal.append(tile)
        return retVal
    
    def pickUpTopGrabbableItem(self):
        level,coords = self.actor.location
        levelMemory = self.memory.getLevelMemory(level.number)
        items = levelMemory.itemMap.get(coords)
        for item in reversed(items):
            if item.grabbable:
                mod_verbs.staticPickUpVerb.doIt(self.actor,item,None)
                return True
        return False
    
    def takeTurn(self):
        AIBrain.takeTurn(self)
        actor = self.actor
        
        iteration = 1
        
        finished = False
        
        while not finished:
            if iteration > 1000:
                raise Exception, "Infinite loop for Janitor"
            print 'In janitor loop, iteration %s' % iteration
            iteration += 1
            
            itemTiles = self.lookForGrabbableItems()
            if itemTiles:
                destination = self.findClosestTile(itemTiles)
                if destination == actor.location[1]:
                    if actor.AP >= mod_verbs.staticPickUpVerb.AP:
                        self.pickUpTopGrabbableItem()
                    else:
                        finished = True
                else:
                    finished = self.travel(destination) # If we didn't move at all, our turn is over.
            else:
                self.moveRandomly()
                finished = True

mopPrototype = mod_item.ItemPrototype('MOP',grabbable=True)
mopPrototype.verbs.append(Whack(1))
janitorPrototype = mod_actor.ActorPrototype('JANITOR', maxHP=4, maxAP=10, APperTurn=7, brainPrototype=JanitorBrain, startingItemPrototypes=[mopPrototype])
